package kr.pe.johnkim.carrotpoint.mobile.controller;

import kr.pe.johnkim.carrotpoint.mobile.domain.CheckMileageMember;
import kr.pe.johnkim.carrotpoint.mobile.domain.ImageFile;
import kr.pe.johnkim.carrotpoint.mobile.service.CheckMileageMemberService;
import kr.pe.johnkim.carrotpoint.mobile.util.CheckMileageCommon;
import kr.pe.johnkim.carrotpoint.mobile.util.CheckMileageConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

/**
 * @author : johnkim <cale9797@gmail.com / Bettersoft, Inc.>
 * @date: 12. 12. 31.
 */
@Controller
@RequestMapping(value = "/checkMileageMemberController")
public class CheckMileageMemberController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(CheckMileageMemberController.class);

    @Autowired
    CheckMileageMemberService checkMileageMemberService;

    @Autowired
    CheckMileageCommon checkMileageCommon;

    @Autowired
    CheckMileageConstant checkMileageConstant;

    /**
     * 테스트용 POST 메소드이다.
     *
     * @RequestBody annotation 을 이용해서 client 로 부터 받은 json string 을 domain object 로 변환한다.
     * 처리 결과를 @ResponseBody annotation 을 이용해서 json string 으로 변환해서 전송한다.
     *
     * 위의 두 annotation 은 jackson 에서 처리한다.
     *
     * http://localhost:8080/rest/checkMileageMemberController/getMemberList
     */
    @RequestMapping(value = "/getMemberList", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public List<CheckMileageMember> getMemberList(@RequestBody CheckMileageMember checkMileageMember) throws Exception {
        logger.info("getMemberList");

        logger.info("checkMileageId : {}", checkMileageMember.getCheckMileageId());
        logger.info("password       : {}", checkMileageMember.getPassword());
        logger.info("phoneNumber    : {}", checkMileageMember.getPhoneNumber());
        logger.info("nickName       : {}", checkMileageMember.getNickName());

        return checkMileageMemberService.getMemberList(checkMileageMember);
    }

    /**
     * 이미지 파일을 전송 받아서 저장한 뒤 결과를 반환 한다.
     *
     * 원본 이미지 파일은 "/upload/profile/" 에 원본 포멧과 동일 하게 저장 하고,
     * 썸네일 이미지 파일을 만든 뒤 "/upload/thumb/" 에 PNG 포멧 으로 저장 한다.
     *
     *
     * @param checkMileageId
     * @param imageFile
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile01", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CheckMileageMember uploadFile01(
            HttpServletRequest request,
            @RequestParam("checkMileageId") String checkMileageId,
            @RequestParam("nickName") String nickName,
            @RequestParam("imageFile") MultipartFile imageFile,
            @RequestParam("imageFileName") String imageFileName) throws Exception {
        logger.info("uploadFile01");

        int thumbnail_width = 120;
        int thumbnail_height = 120;

        CheckMileageMember result = new CheckMileageMember();

        try {
            logger.info("checkMileageId         : {}", checkMileageId);
            logger.info("checkMileageId encoded : {}", checkMileageCommon.getEncodedPassword(checkMileageId));
            logger.info("nickName               : {}", nickName);
            logger.info("imageFile name         : {}", imageFileName);
            logger.info("imageFile size         : {}", imageFile.getSize()+" byte");

            if(!imageFile.isEmpty()) {
                // context path 를 가져 온다.
                String uploadPath = request.getSession().getServletContext().getRealPath("/");

                logger.info("path : {}", uploadPath + "upload/profile/");

                ImageFile parameter = new ImageFile();
                parameter.setCheckMileageId(checkMileageId);
                parameter.setImageFile(imageFile);
                parameter.setUploadPath(uploadPath + "upload/profile/");

                // 서버에 원본 이미지 파일을 저장 한다.
                ImageFile resultImageFile = checkMileageCommon.uploadProfileImage(parameter);

                String tempThumbnailImageFileName = resultImageFile.getTempFileName().substring(0, resultImageFile.getTempFileName().length()-4);

                File originalImageFile = new File(uploadPath + "upload/profile/" + resultImageFile.getTempFileName());
                // 생성 하려는 썸네일 이미지 파일의 확장자를 붙인다.
                File thumbnailImageFile = new File(uploadPath + "upload/thumbnail/" + tempThumbnailImageFileName + ".png");

                ImageFile thumbnailParameter = new ImageFile();
                thumbnailParameter.setOriginalImageFile(originalImageFile);
                thumbnailParameter.setThumbnailImageFile(thumbnailImageFile);
                thumbnailParameter.setThumbnailWidth(thumbnail_width);
                thumbnailParameter.setThumbnailHeight(thumbnail_height);

                // 서버에 썸네일 이미지 파일을 만든 뒤 저장 한다.
                String thumbnailImageFileName = checkMileageCommon.createThumbnailImageFile(thumbnailParameter);

                logger.info("originalImageFileName on server  : {}", resultImageFile.getTempFileName());
                logger.info("thumbnailImageFileName on server : {}", thumbnailImageFileName);

                result.setResult("SUCCESS");
            } else {
                logger.info("Image file is empty.");
            }
        } catch (Exception e) {
            result.setResult("FAIL");
        }

        return result;
    }

    @RequestMapping(value = "/uploadFile02", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CheckMileageMember uploadFile02(
            @RequestParam("checkMileageMember") CheckMileageMember checkMileageMember) throws Exception {
        logger.info("uploadFile02");

        CheckMileageMember result = new CheckMileageMember();

        try {


//            logger.info("imageFile name : {}", imageFileName);
//            logger.info("imageFile size : {}", imageFile.getSize()+" byte");
            logger.info("checkMileageId : {}", checkMileageMember.getCheckMileageId());



            result.setResult("SUCCESS");
        } catch (Exception e) {
            result.setResult("FAIL");
        }


        return result;
    }
}
